import java.util.concurrent.ArrayBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:38917
 * Date:2025/4/14
 * Time:21:55
 */
class MyTimerTask implements Comparable<MyTimerTask> {
    private final long time;
    private final Runnable runnable;
    //
    public MyTimerTask(long delay, Runnable runnable){
        this.time = System.currentTimeMillis() + delay;
        this.runnable = runnable;
    }
    //
    public void run(){
        this.runnable.run();
    }
    //
    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time - o.time);
    }
    //
    public long getTime(){
        return this.time;
    }
}

public class MyTimer {
    private final ArrayBlockingQueue<MyTimerTask> queue = new ArrayBlockingQueue<>(10);
    private final Object locker = new Object();
    public void schedule(Runnable runnable, long delay){
        synchronized(locker) {
            MyTimerTask task = new MyTimerTask(delay, runnable);
            queue.add(task);
            locker.notify();
        }
    }
    public MyTimer(){
        Thread thread = new Thread(() -> {
            while (true) {
                synchronized(locker) {
                    try {
                        while (queue.isEmpty()) {
                            locker.wait();
                        }
                        MyTimerTask task = queue.peek();
                        long curTime = System.currentTimeMillis();
                        if (curTime >= task.getTime()) {
                            queue.poll();
                            task.run();
                        } else {
                            locker.wait(task.getTime() - curTime);
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });
        thread.start();
    }
    //
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(()-> System.out.println("Hello World :" + 3000),3000);
    }
}
